<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel="stylesheet" href="/public/bootstrap.min.css">
  <link rel="stylesheet" href="/public/bootstrap-icons-141.css">
  <link rel="stylesheet" href="/public/style-light.css">
  
  <script src="/public/jquery.min.js"></script>
  <script src="/public/dayjs.min.js"></script>
  <script src="/public/bootstrap.bundle.min.js"></script>
  <script src="/public/clipboard.min.js"></script>
  <script src="/public/util.js"></script>
  
  <title>Tag - localtags</title>
</head>
<body>
  <div id="root" class="container" style="max-width: 775px; min-width: 400px;"></div>
  <script>

const tag_name = getUrlParam('name');

const Alerts = CreateAlerts();

const [InfoBtn, InfoMsg] = CreateInfoPair('使用说明', m('ul').append([
  m('li').text('点击 copy 按钮可复制标签组。点击标签名前的铅笔图标可显示/隐藏修改标签名的表单。'),
  m('li').text('按 F12 进入控制台输入 deletetag("标签名") 可删除标签。注意：一旦删除无法恢复。'),
  m('li').text('如果删除标签可能导致一个文件完全没有标签，会提示删除失败，并返回文件 ID。'),
]));

const Navbar = {
  view: () => m('nav').addClass('navbar navbar-light bg-light').append([
    m('div').addClass('container-fluid').append([
      m('a').attr({title:'main menu',href:'/light/home',type:'button'}).addClass('btn btn-outline-dark').append(
        m('i').addClass('bi bi-house-door'),
      ),
      m('span').addClass('navbar-brand').append([
        'Tag', ' ', m(InfoBtn),
      ]),
      m('a').attr({title:'All Tags',href:'/light/tags',type:'button'})
        .addClass('btn btn-outline-dark').append(
          m('i').addClass('bi bi-tags')
      ),
    ]),
  ]),
};

const GroupList = cc('div');
GroupList.prepend = (group) => {
  const item = createTagGroup(group);
  $(GroupList.id).prepend(m(item));
  item.init();
};

const NameInput = cc('input');
const CheckBtn = cc('button');
const RenameBtn = cc('button');
const Form = cc('div');
Form.view = () => m('div').attr({id:Form.raw_id}).addClass('input-group').hide().append([
  m(NameInput).addClass('form-control').focus(Form.showCheckBtn),
  m(CheckBtn).text('check').attr({type:'button'})
    .addClass('btn btn-outline-secondary').click(Form.check),
  m(RenameBtn).text('rename').attr({type:'button'})
    .addClass('btn btn-outline-primary').hide().click(Form.rename),
]);

Form.toggle = () => {
  const display = $(Form.id).css('display');
  if (display == 'none') {
    $(Form.id).show('fast', () => { $(NameInput.id).focus() });
  } else {
    $(Form.id).hide();
  }
};

Form.showCheckBtn = () => {
  $(CheckBtn.id).show();
  $(RenameBtn.id).hide();
}

Form.check = () => {
  const input = $(NameInput.id);
  const name = getTag(input.val());
  if (!name || name == tag_name) { input.focus(); return; }

  const body = new FormData();
  body.append('new-name', name);
  ajax({method:'POST',url:'/api/is-tag-exist',alerts:Alerts,buttonID:CheckBtn.id,body:body},
      (tagIsExist) => {
        input.val('#'+name);
        $(CheckBtn.id).hide();
        $(RenameBtn.id).show();
        if (tagIsExist) Alerts.insert('info', `标签 #${name} 已存在，执行改名会合并标签。`);
      });
};

Form.rename = () => {
  const new_name = getTag($(NameInput.id).val());
  const body = new FormData();
  body.append('old-name', tag_name);
  body.append('new-name', new_name);
  ajax({method:'POST',url:'/api/rename-tag',alerts:Alerts,buttonID:RenameBtn.id,body:body},
      () => {
        $(Form.id).hide();
        $(GroupList.id).hide();
        Alerts.clear();
        Alerts.insert('info', '重命名成功时会自动刷新页面');
        Alerts.insert('success', `正在重命名: ${tag_name} --> ${new_name}`);
        window.setTimeout(() => {window.location = '/light/tag?name='+new_name}, 3000);
      });
}

const Name = cc('span');
const NameBtn = cc('i');
const NameArea = cc('div', null, [
  m(NameBtn).attr({title:'rename'}).addClass('bi bi-pencil-square').css('cursor', 'pointer').click(Form.toggle),
  ' ',
  m(Name).addClass('h5'),
]);

$('#root').append([
  m(Navbar).addClass('mt-2 mb-5'),
  m(InfoMsg).hide(),
  m(Loading),
  m(NameArea).hide(),
  m(Form),
  m(Alerts),
  m(GroupList),
  m(Spacer),
  m(BottomLine),
]);
  
init()

function init() {
  $(Name.id).text(tag_name);
  const body = new FormData();
  body.append('name', tag_name);
  
  ajax({method:'POST',url:'/api/get-groups-by-tag',alerts:Alerts,body:body},
      (groups) => {
        $(NameArea.id).show();
        if (!groups || groups.length == 0) {
          Alerts.insert('info', '找不到与该标签相关的文件');
          return;
        }
        groups.forEach(GroupList.prepend);
      }, null, () => {
        Loading.hide();
      });
}

function createTagGroup(group) {
  const self = cc('div');

  self.view = () => m('div').attr({id: self.raw_id}).addClass('TagGroup card my-3').append([
    m('div').addClass('card-body').append([
      m('div').addClass('Tags'),
    ]),
  ]);

  self.init = () => {
    const tagGroupStr = addPrefix(group);
    const tagsElem = $(self.id + ' .Tags');
    group.forEach(tag => {
      if (tag == tag_name) {
        const item = m('span').text(tag).addClass('badge bg-light text-dark').css({cursor:'default'});
        tagsElem.append(item);
      } else {
        const item = m('a').text(tag).addClass('badge bg-success text-white text-decoration-none')
          .attr({href:'/light/tag?name=' + encodeURIComponent(tag)});
        tagsElem.append(item);
      }
    });

    const copyBtn = m('span').text('copy').addClass('CopyBtn badge bg-primary');
    tagsElem.append(copyBtn);

    const groupLink = '/light/search?tags=' + encodeURIComponent(tagGroupStr);
    const groupItem = m('a').text('search').attr({title:'search tag group', href:groupLink})
      .addClass('badge bg-primary text-white text-decoration-none');
    tagsElem.append(groupItem);

    const clipboard = new ClipboardJS(self.id+' .CopyBtn', {
      text: () => { return tagGroupStr; }
    });
    clipboard.on('success', () => {
      $(self.id+' .CopyBtn').text('copied').removeClass('bg-primary').addClass('bg-secondary');
    });

  };

  return self;
}

// 提取出一个标签。
function getTag(tagsString) {
  let trimmed = tag_replace(tagsString);
  if (trimmed.length == 0) {
    return false;
  }
  let arr = trimmed.split(/ +/);
  return arr[0];
}

function deletetag(name) {
  const body = new FormData();
  body.append('tag-name', name);
  ajax({method:'POST',url:'/api/delete-tag',body:body},
      () => {
        console.log('已删除 #' + name);
      });
}

  </script>
</body>
</html>